import React, {Component} from 'react';
import moment from 'moment';
import {
  Form,
  Input,
  Tag,
  Select,
  Calendar,
  Badge,
  Radio,
  Button,
  Icon,
  Table,
  DatePicker,
  Popover,
  Tabs,
  Checkbox,
  Modal,
  Timeline
} from 'antd';
import Menu from "./Menu";
import LetterElment from "../../../components/LetterElment";
import {
  taskAttendanceAndTrackAttendanceRecord,
  taskAttendanceAndTrackTaskLog,
  taskComTaskImplAttendanceStatus,
  taskComTaskImplQueryTrack,

  taskTrackSelectImplementMonth,
  taskTrackListImplement,
} from "../../../services/api";

import '../Task.less';

const FormItem = Form.Item;
const {Search} = Input;
const {Option} = Select;
const {TabPane} = Tabs;
const monthFormat = 'YYYY-MM';
const {MonthPicker} = DatePicker;
const CheckboxGroup = Checkbox.Group;
/* 查看轨迹 */
const guiji = [
  {
  day: "18",
  date: "2017-12-18",
  selected: true,
}, {
  day: "18",
  date: "2017-12-18",
  selected: true,
}];

/* 任务日志 */
const tasklog = [
  {
  time: "10:23",
  content: '我已开始执行任务，xxxx地方一切正常。我已开始执行任务，xxxx地方一切正常。我已开始执行任务，xxxx地方一切正常。我已开始执行任务，xxxx地方一切正常。',
  imglist: ["https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png", 'http://img.taopic.com/uploads/allimg/120727/201995-120HG1030762.jpg']
},
  {
    time: "5:23",
    content: '我已开始执行任务，xxxx地方一切正常。我已开始执行任务，xxxx地方一切正常。我已开始执行任务，xxxx地方一切正常。我已开始执行任务，xxxx地方一切正常。',
    imglist: ["http://pic10.nipic.com/20101001/2531170_011837344719_2.jpg", 'http://pic.58pic.com/58pic/15/24/50/43Q58PICkj4_1024.jpg']
  },
  {
    time: "7:2",
    content: '我已开始执行任务，xxxx地方一切正常。我已开始执行任务，xxxx地方一切正常。我已开始执行任务，xxxx地方一切正常。我已开始执行任务，xxxx地方一切正常。',
    imglist: ["http://f2.topitme.com/2/6a/bc/113109954583dbc6a2o.jpg", 'http://pic17.nipic.com/20111021/8289149_105725398120_2.jpg']
  }];

/* yi出勤异常，zheng出勤正常,que缺岗 xiu休息 */
const tag = {
  yi: <i className="exclamation-box"><Icon type="exclamation"/></i>,
  zheng: <Icon type="check-square"/>,
  que: <Icon type="close-square"/>,
  xiu: <LetterElment name="xiu" type="tag"/>,
};


const options = [
  {label: <LetterElment name="a"/>, value: 'Apple'},
  {label: <LetterElment name="b"/>, value: 'Pear'},
  {label: <LetterElment name="c"/>, value: 'Orange'},
  {label: <LetterElment name="d"/>, value: 'xiu'},
];


@Form.create()
export default class TaskDetailAttendanceTrack extends Component {
  state = {
    disabled: false,
    visible1: false,
    visible2: false,
    currentTab: "2",
    comTaskId:this.props.comTaskId,
    perName: '',//人员名称
    perId: '',//人员id
    monthDate: '2018-01',//月份选择
    attendStatus: '',//状态
    monthValue: 0,
    monthDateArray: [],
    titleList: {},//头部标识栏
    attendanceRecordList: [],//人员每月出勤记录
    codeOne: {},//出勤是否正常对照
    codeTwo: {},//出勤是否正常对照
    sArray: [],//轨迹弹窗右侧天数
    selectedDate: '',//点击日志时所查看的每月的几号
    totalTime: '',//轨迹弹窗的执行时长
    statusList: [],//轨迹弹窗的左下方的轨迹切换
    previewVisible: false,//日志的图片弹窗
    subvalUrl:'',//日志中的查看图片
    tasklog:[],//任务日志内容

    addressLatitude:"24.49995",
    addressLongitude:"118.142337",
    showInitialMarker:true,
    pagenav: {
      current: 1,
      pageSize: 10,
      showQuickJumper: true,
      showSizeChanger: true,
      showTotal: total => `总共 ${total} 条`,
      onShowSizeChange: (current, pageSize) => {
        const pagenav = Object.assign({}, this.state.pagenav);
        pagenav.current = current;
        pagenav.pageSize = pageSize;
        this.setState({pagenav});
        // setTimeout(() => {
        //   this.bbdExampersonPage();
        // });
      },
      onChange: (page, pageSize) => {
        const pagenav = Object.assign({}, this.state.pagenav);
        pagenav.current = page;
        pagenav.pageSize = pageSize;
        this.setState({pagenav});
        // setTimeout(() => {
        //   this.bbdExampersonPage();
        // });
      },
      total: 0,
    }
  };

  componentDidMount() {
    this.getDateAndMonth();//得到当前的年月(没什么用)
    this.getActualMonth();
    this.renderTitleList();
    //地图script
    this.loadMapScript();
  }

  loadMapScript = () => {
    const script = document.createElement("script");
    script.src =
      "http://webapi.amap.com/maps?v=1.4.4&key=9066916e054aa3083a6f081a2a9f9d7a";
    document.body.appendChild(script);

    const script2 = document.createElement("script");
    script2.src =
      "http://cache.amap.com/lbs/static/addToolbar.js";
    document.body.appendChild(script2);

  };
  initialMap=(lng='116.397428',lat='39.90923')=>{
    const that = this;
    const { AMap } = window;
    let map = new AMap.Map('mapContainer', {
      resizeEnable: true,
      zoom:12,
      center: [lng,lat]
    });
    this.setState({map});
  };


  getDateAndMonth = () => {
    let date = new Date();
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    month = (month < 10 ? "0" + month : month);
    let mydate = (year.toString() + '-' + month.toString());
    let date_value = this.getDaysInOneMonth(year, month);
    console.log('当前月份的天数', date_value);
    this.renderDateArray(date_value);
    this.setState({
      monthDate: mydate,
    },()=>{
        console.log('当前月份',this.state.monthDate);
    });
  };

  getActualMonth = () => {
    taskTrackSelectImplementMonth({
      comTaskId: this.state.comTaskId,
    }).then((data) => {
      if(data.data){
        this.setState({
          monthDate:data.data
        },()=>{
          this.renderDataAttendance();
        })
      }
    })
  };

  renderDataAttendance = () => {
    taskAttendanceAndTrackAttendanceRecord({
      comTaskId: this.state.comTaskId,
      perName: this.state.perName,
      paramMonth: this.state.monthDate,
      attendStatus: this.state.attendStatus
    }).then((data) => {
      console.log('123456', data.data);
      if (data.data) {
        this.setState({
          attendanceRecordList: data.data,
        });
      }
    }).catch(err => {
    });

    console.log('1',this.state.comTaskId);
    console.log('2',this.state.perName);
    console.log('3',this.state.monthDate);
    taskTrackListImplement({
      comTaskId:888,
      perName: '',
      month: '',
    }).then((data) => {
      console.log('数据数据AAA', data);
    }).catch(err => {
    });
  };

  renderGuiJiDataList = (sVal) => {
    console.log(sVal, '选中的人员id');
    this.setState({
      perId: sVal,
      selectedDate: this.state.monthDate + '-' + '01'
    });
    console.log(this.state.monthDateArray, '月份月份');
    let sArray = [];
    this.state.monthDateArray.map((v) => {
      sArray.push({
        day: v,
        date: (this.state.monthDate.toString() + '-' + v),
        selected: false,
      })
    });
    sArray[0]['selected'] = true;
    this.setState({
      sArray: sArray
    });

    taskComTaskImplQueryTrack({
      comTaskId: this.state.comTaskId,
      perId: sVal,
      dates: this.state.monthDate + '-' + '01'
    }).then((data) => {
      console.log('返回的数据',data.data);
      if (data.data) {
        this.setState({
          totalTime: data.data.totalTime,
          statusList: data.data.status,
        });
      }
    }).catch(err => {
    });
  };

  renderTitleList = () => {
    taskComTaskImplAttendanceStatus({}).then((data) => {
      console.log('234567', data.data);
      if (data.data) {
        this.setState({
          codeOne: data.data.code2,
          codeTwo: data.data.code,
        }, () => {
          console.log('111', this.state.codeOne);
          console.log('222', this.state.codeTwo);
        })
      }
    })
  };

  //获得某年某月的天数
  getDaysInOneMonth = (year, month) => {
    month = parseInt(month, 10);
    let d = new Date(year, month, 0);
    return d.getDate();
  };

  renderDateArray = (sValue) => {
    const sWed = [];
    for (let i = 1; i <= sValue; i++) {
      i = (i < 10 ? "0" + i.toString() : i.toString());
      sWed.push(i);
    }
    sWed.sort((a, b) => parseInt(a) - parseInt(b));
    this.setState({
      monthDateArray: sWed,
    })
  };

  getListData = (value) => {
    let listData;
    switch (value.date()) {
      case 8:
        listData = [
          {type: 'unusual', content: 1},
          {type: 'normal', content: 2},
          {type: 'lack', content: 3},
          {type: 'xiu', content: 3},
        ];
        break;
      case 10:
        listData = [
          {type: 'unusual', content: 1},
          {type: 'normal', content: 2},
          {type: 'lack', content: 3},
          {type: 'xiu', content: 3},
        ];
        break;
      case 15:
        listData = [
          {type: 'unusual', content: 1},
          {type: 'normal', content: 2},
          {type: 'lack', content: 3},
          {type: 'xiu', content: 3},
        ];
        break;
      default:
    }
    return listData || [];
  };

  getMonthData = (value) => {
    if (value.month() === 8) {
      return 1394;
    }
  };

  renderTableHeadList = () => {
    const columnsData = [];
    this.state.monthDateArray.map((v, k) => {
      columnsData.push({
        title: v,
        dataIndex: (this.state.monthDate.toString() + '-' + v),
        key: (this.state.monthDate.toString() + '-' + v),
        render: (text, record, index) => {
          let keysArray = [];
          let valuesArray = [];
          for (let p1 in text) {
            if (text.hasOwnProperty(p1)) {
              keysArray.push(p1);
              valuesArray.push(text[p1]);
            }
          }
          const content = (
            <div className="taskdetailattendancetrack-popover">
              {this.renderStatusList(keysArray, valuesArray)}
            </div>
          );
          return (
            <Popover content={content}>
              <div className="TaskDetailAttendanceTrack-table-tag-list" key={k}>
                {this.renderTrackDataList(keysArray)}
              </div>
            </Popover>);
        }
      });
    });
    columnsData.sort((a, b) => parseInt(a.title) - parseInt(b.title));
    columnsData.splice(0, 0, {
      title: '姓名',
      dataIndex: 'perName',
      key: 'perName',
      width: 120,
      fixed: 'left',
    });
    columnsData.push({
      title: '操作',
      dataIndex: 'cao',
      key: '6',
      render: (text, record, index) => {
        return (<span className="span_hover" style={{fontSize: '12px', color: '#0e6bf2'}} onClick={() => {
          this.setState({visible1: true});
          this.renderGuiJiDataList(record.perId);

          setTimeout(() => {
            //初始化地图
            this.initialMap(this.state.addressLongitude,this.state.addressLatitude);
          }, 200);
        }}>轨迹</span>);
      },
      width: 80,
      fixed: 'right',
    });
    return columnsData;
  };

  renderTrackDataList = (sVal) => {
    return sVal.map((v) => {
      return (
        tag[this.state.codeOne[v]]
      )
    })
  };

  renderStatusList = (sValOne, sValTwo) => {
    return sValOne.map((v, k) => {
      if (v === '0') {
        return <Badge status="processing" text={sValTwo[k]} key={k}/>
      }
      if (v === '1') {
        return <Badge status="success" text={sValTwo[k]} key={k}/>
      }
      if (v === '2') {
        return <Badge status="default" text={sValTwo[k]} key={k}/>
      }
      if (v === '3') {
        return <Badge status="warning" text={sValTwo[k]} key={k}/>
      }
    })
  };

  renderMapDataList = () => {
    let keysArray = [];
    let valuesArray = [];
    //
    // console.log('数据数据',this.state.statusList);
    if(this.state.statusList.length >= 1){
      this.state.statusList.map((v)=>{
        for (let psd in v) {
          keysArray.push(psd);
          valuesArray.push(v[psd]);
        }
        });
      console.log('111111',keysArray);
      console.log('222222',valuesArray);
    }
    return keysArray.map((v, k) => {
      if (v === '0') {
        return <Badge status="processing" text={valuesArray[k]} key={k}/>
      }
      if (v === '1') {
        return <Badge status="success" text={valuesArray[k]} key={k}/>
      }
      if (v === '2') {
        return <Badge status="default" text={valuesArray[k]} key={k}/>
      }
      if (v === '3') {
        return <Badge status="warning" text={valuesArray[k]} key={k}/>
      }
    })
  };

  renderTableContentList = () => {
    const dataSourceList = this.state.attendanceRecordList.map((v, k) => {
      const value = v;
      value.key = v.perId;
      return value;
    });
    return dataSourceList;
  };


  columns = [{
    title: '姓名',
    dataIndex: 'perName',
    key: 'name',
    width: 80,
    fixed: 'left',
  },
    {
      title: '10',
      dataIndex: 'age',
      key: '1',
      render: () => {
        const content = (
          <div className="taskdetailattendancetrack-popover">
            <Badge status="default" text="缺岗:09：00~12:00"/>
            <Badge status="warning" text="迟到:09：00~12:00"/>
            <Badge status="processing" text="正常:09：00~12:00"/>
          </div>
        );
        return (
          <Popover content={content} trigger="click">
            <div className="TaskDetailAttendanceTrack-table-tag-list">
              {tag.xiu}
              {tag.unusual}
              {tag.normal}
              {tag.lack}
            </div>
          </Popover>);
      }
    },
    {
      title: '11',
      dataIndex: 'age',
      key: '2',
      render: () => {
        const content = (
          <div className="taskdetailattendancetrack-popover">
            <Badge status="default" text="缺岗:09：00~12:00"/>
            <Badge status="warning" text="迟到:09：00~12:00"/>
            <Badge status="processing" text="正常:09：00~12:00"/>
          </div>
        );
        return (
          <Popover content={content} trigger="click">
            <div className="TaskDetailAttendanceTrack-table-tag-list">
              {tag.xiu}
              {tag.unusual}
              {tag.normal}
              {tag.lack}
            </div>
          </Popover>);
      }
    },
    {
      title: '12',
      dataIndex: 'age',
      key: '3',
      render: () => {
        return (<span onClick={() => {
          this.setState({visible1: true});
        }} className="p-blue-color">轨迹</span>);
      }
    }];

  dataSource = [{
    key: '1',
    perName: '胡彦斌',
    age: 32,
    address: '西湖区湖底公园1号'
  }, {
    key: '2',
    name: '胡彦祖',
    age: 42,
    address: '西湖区湖底公园1号'
  }];

  monthCellRender = (value) => {
    const num = this.getMonthData(value);
    return num ? (
      <div className="notes-month">
        <section>{num}</section>
        <span>Backlog number</span>
      </div>
    ) : null;
  };

  dateCellRender = (value) => {
    const listData = this.getListData(value);
    return (
      <div className="list">
        {
          listData.map((item, index) => {
            return <div className="tag-item" key={index}>{tag[item.type]}{item.content}人</div>;
          })
        }
      </div>
    );
  };

  //时间年月的变化
  dateValueChange = (date, dateString) => {
    // console.log('时间年月的变化', dateString);
    let year = dateString.substring(0, 4);
    let month = dateString.substring(5);
    let s_value = this.getDaysInOneMonth(year, month);
    console.log('123', dateString);
    console.log('123', s_value);
    this.renderDateArray(s_value);
    this.setState({
      monthDate: dateString.toString(),
      monthValue: s_value,
    });
  };

  /* 列表模式 */
  renderListPanel = () => {
    return (<div className="tabPanel">
      <Table pagination={this.state.pagenav} bordered dataSource={this.renderTableContentList()}
             columns={this.renderTableHeadList()} scroll={{x: 6500}}/>
    </div>);
  };
  /* 日历模式 */
  renderDatePanel = () => {
    return (<div className="tabPanel">
      <Calendar onSelect={(date) => {
        const day = new Date(date["_d"]);
        this.setState({visible1: true});
        console.log(day.getDate());
      }} className="TaskDetailPersonnelPlacement-Calendar" dateCellRender={this.dateCellRender}
                monthCellRender={this.monthCellRender}/>
    </div>);
  };

  //点击搜索
  searchContent = (sVal) => {
    taskAttendanceAndTrackAttendanceRecord({
      comTaskId: this.state.comTaskId,
      perName: sVal,
      paramMonth: this.state.monthDate,
    }).then((data) => {
      if (data.data) {
        this.setState({
          attendanceRecordList: data.data
        });
      }
    }).catch(err => {
    });
  };

  renderDataStatusWed = (s1, s2, s3) => {
    console.log('s1s1s1', s1);
    console.log('s2s2s2', s2);
    console.log('s3s3s3', s3);
    const {sArray} = this.state;
    if (s2 === false) {
      sArray.map((v) => {
        v.selected = false
      });
      sArray[s3].selected = true;
      this.setState({
        sArray,
        selectedDate: s1
      });
      taskComTaskImplQueryTrack({
        comTaskId: this.state.comTaskId,
        perId: this.state.perId,
        dates: s1,
      }).then((data) => {
        console.log('datadata', data.data);
        if (data.data) {
          this.setState({
            totalTime: data.data.totalTime,
            statusList: data.data.status
          })
        }
      }).catch(err => {
      });
    }
  };

  renderTaskLogDataList = () => {
    this.setState({visible2: true});
    taskAttendanceAndTrackTaskLog({
      comTaskId: this.state.comTaskId,
      perId: this.state.perId,
      dates: this.state.selectedDate
    }).then((data) => {
      console.log('951', data);
      if(data.data){
        this.setState({
          tasklog:data.data,
        })
      }
    });
  };

  render() {

    const {getFieldDecorator} = this.props.form;

    return (
      <div className="TaskDetail TaskDetailPersonnelPlacement TaskDetailAttendanceTrack">
        <div className="form">
          <Form
            onSubmit={this.handleSubmit}
            layout="inline"
          >
            <div className="Icon-list">
              {tag.yi}出勤异常
              {tag.zheng}出勤正常
              {tag.que}缺岗
              {tag.xiu}休息
            </div>
            <div className="form-box">
              <FormItem>
                {getFieldDecorator('addressOne', {
                  initialValue: moment(this.state.monthDate, monthFormat),
                })(
                  <MonthPicker format={monthFormat} onChange={this.dateValueChange}/>
                )}
              </FormItem>
              {/*<FormItem>*/}
              {/*{getFieldDecorator('address', {*/}
              {/*rules: [{ message: '请选择' }],*/}
              {/*})(*/}
              {/*<Select style={{ width: 104 }} disabled={this.state.disabled} placeholder="搜索条件">*/}
              {/*<Option value="">请选择</Option>*/}
              {/*<Option value="1">缺岗</Option>*/}
              {/*<Option value="2">迟到</Option>*/}
              {/*<Option value="3">正常</Option>*/}
              {/*</Select>*/}
              {/*)}*/}
              {/*</FormItem>*/}
              <FormItem>
                {getFieldDecorator('sdsd', {
                  rules: [{message: '请输入搜索内容'}],
                })(
                  <Search
                    placeholder="请输入搜索内容"
                    // onSearch={value => console.log(value)}
                    onSearch={value => this.searchContent(value)}
                    style={{width: 200}}
                    enterButton
                  />
                )}
              </FormItem>
              {/*<Radio.Group value={this.state.currentTab} className="ant-radio-group-self" >*/}
              {/*<Radio.Button onClick={() => { this.setState({ currentTab: "1" }); }} value="1">日历模式</Radio.Button>*/}
              {/*<Radio.Button onClick={() => { this.setState({ currentTab: "2" }); }} value="2">列表模式</Radio.Button>*/}
              {/*</Radio.Group>*/}
            </div>
          </Form>
          {this.state.currentTab === "1" ? this.renderDatePanel() : this.renderListPanel()}
        </div>
        {/* 查看轨迹 */}
        <Modal
          title={null}
          visible={this.state.visible1}
          width={880}
          footer={[]}
          onCancel={() => {
            this.setState({visible1: false, perId: '', totalTime: '', statusList: [], selectedDate: ''});
          }}
          maskClosable
          closable={false}
          wrapClassName="TaskDetailAttendanceTrack-modal"
        >
          <div className="map-box">
            <div className="map-header">
              <span className="map-title-time">执行时长：{this.state.totalTime}</span>
              <span onClick={() => {
                this.renderTaskLogDataList();
              }} className="map-log">日志</span>
            </div>
            <div className="map-tip">
              {this.renderMapDataList()}
            </div>
            {/*className="map-content"*/}
            <div id="mapContainer" style={{width:'100%', height:'100%'}}>
            </div>
          </div>
          <div className="user-list">
            <h3>查看轨迹</h3>
            <div className="usr-list-box" style={{paddingBottom: '15px'}}>
              {/*<div className="item-all">*/}
              {/*全部*/}
              {/*</div>*/}
              {this.state.sArray.map((val, index) => {
                return (<div key={index} className={val.selected ? "item selected" : "item"} onClick={() => {
                  this.renderDataStatusWed(val.date, val.selected, index)
                }}>
                  <span>{val.day}</span>
                  <Icon type="check-circle"/>
                  <p>{val.date}</p>
                </div>);
              })}
            </div>
          </div>
        </Modal>

        {/* 查看轨迹-日志 */}
        <Modal
          title="任务日志"
          visible={this.state.visible2}
          width={520}
          footer={[]}
          onCancel={() => {
            this.setState({visible2: false,tasklog:[]});
          }}
          maskClosable
          wrapClassName="TaskDetailAttendanceTrack-task-log"
        >
          {this.state.tasklog.length > 0 ? <Timeline>
            {this.state.tasklog.map((val, index) => {
              return (<Timeline.Item key={index}>
                <div className="time">{val.createTime}</div>
                <div className="content">
                  <p>{val.feedbackContent}</p>
                  <div className="imglist">
                    {val.photoUrl ? val.photoUrl.split(',').map((subval, i) => {
                      return <div key={i} className="imgwrap">
                        <img src={subval} alt="" onClick={() => {
                          this.setState({
                            previewVisible: true,
                            subvalUrl: subval
                          })
                        }}/>
                      </div>;
                    }) : ''}
                  </div>
                </div>
              </Timeline.Item>);
            })}
          </Timeline> : <p style={{textAlign:'center',fontSize:'18px'}}>暂未上传日志！</p>}
        </Modal>

        {/* 查看轨迹-日志-查看图片 */}
        <Modal visible={this.state.previewVisible} footer={null}
               onCancel={() => {
          this.setState({previewVisible: false, subvalUrl: ''})
        }}>
          <img src={this.state.subvalUrl} alt="" style={{display: 'block', width: '100%', height: 'auto'}}/>
        </Modal>
        {/*<div id="mapContainer" style={{width:'300px', height:'210px'}}>*/}
        {/*</div>*/}
      </div>
    );
  }
}

